package 我的Java学习_算法基础.day_04;

public class _068_矩阵运算乘法 {

    public static void main(String[] args) {
        int[][] a={
                {1,0,3,-1},
                {2,1,0,2}
        };

        int[][] b={
                {4,1,0},
                {-1,1,3},
                {2,0,1},
                {1,3,4}
        };
//        int[][] x=getATimesB(a,b);
        long[][] x=matrixMultiply(a,b);
        print(x);
    }

    private static void print(long[][] x) {
        int m = x.length;
        int n = x[0].length;
        for(int i =0;i<m;i++){
            for(int j =0;j<n;j++){
                System.out.print(x[i][j]+"\t");
            }
            System.out.println();
        }
    }

    private static int[][] getATimesB(int[][] a,int[][] b){     //thinking by myself
        int m=a.length;
        int n = b[0].length;
        int[][] x = new int[m][n];
        int[] aHang = new int[a[0].length]; //a的行
        int flag =0;    //指针,最大为a的列数，b的行数
        int[] bLie = new int[b.length];     //b的列
        for(int i=0;i<m;i++){
            while(flag<a[0].length){    //a的i行
                aHang[flag]=a[i][flag];
                flag++;
            }
            flag=0;
            for(int j =0;j<n;j++){
                while(flag<b.length){   //b的j列
                    bLie[flag]=b[flag][j];
                    flag++;
                }
                for(int r = 0;r<flag;r++){
                    x[i][j]+=aHang[r]*bLie[r];
                }
                flag=0;
            }

        }
        return x;
    }
    private static long[][] matrixMultiply(int[][] m1,int[][] m2){
        final int n = m1.length;
        final int m = m1[0].length;
        if(m!=m2.length) throw new IllegalArgumentException();
        final int p = m2[0].length;
        long[][] result = new long[n][p];

        for(int i = 0;i<n;i++){
            for(int j =0;j<p;j++){
                for(int k=0;k<m;k++){
                    result[i][j]+=m1[i][k]*m2[k][j];
                }
            }
        }
        return result;
    }

}
